"""
Description  : 
Version      : 1.0
Author       : seraph
Date         : 2024-10-10 16:28:35
LastEditors  : seraph
LastEditTime : 2024-10-10 17:21:58
"""

"""
Description  : 
Version      : 1.0
Author       : seraph
Date         : 2024-10-10 16:28:35
LastEditors  : seraph
LastEditTime : 2024-10-10 16:48:51
"""

import winreg
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
from tkinter import ttk
from tkinter import simpledialog
import os
import configparser
import subprocess
import sys
import time
import threading
import psutil


# 读配置文件
def get_config():
    config = configparser.ConfigParser()
    config.read("config.ini")
    return config


# 取配置项值
def get_config_value(section, option, default_value=None):
    config = get_config()
    path = config.get(section, option, fallback=None)
    return path


# 写配置文件
def set_config(config):
    with open("config.ini", "w") as f:
        config.write(f)


# HKEY_CLASSES_ROOT\weixin\shell\open\command
# 取微信安装路径
def get_wechat_path():
    result, key = None, None
    try:
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"weixin\shell\open\command")
        value, type_ = winreg.QueryValueEx(key, "")
        result = value.split('"')[1]
    except:
        result = None
    finally:
        if key:
            winreg.CloseKey(key)

    return result


# 若微信路径不存在，则弹出对话框让用户选择路径
def select_wechat_path():
    messagebox.showerror("提示：", "未找到微信安装路径！\r\n请手动选择或重新安装微信！")
    quit_loop = False
    directory = ""
    while not quit_loop:
        directory = filedialog.askdirectory(title="请选择微信所在目录：")
        if not directory:
            result = messagebox.askretrycancel("警告：", "未选择目录！请重试或退出！")
            if not result:
                quit_loop = True
        else:
            if not os.path.exists(os.path.join(directory, "WeChat.exe")):
                result = messagebox.askretrycancel(
                    "错误：",
                    "该目录下未找到微信主程序！\r\n请重试或退出！",
                )
                if not result:
                    quit_loop = True
            else:
                path = directory + "/WeChat.exe"
                quit_loop = True
    return path


# 杀死微信进程
def kill_wechat_process():
    # 遍历取进程名
    kill_wechat = False
    for proc in psutil.process_iter(["pid", "name"]):
        # 检查进程名是否匹配
        try:
            if proc.name().lower() == "wechat.exe":
                # 弹出提示框，如果已经弹出过，则不再弹出
                if not kill_wechat:
                    result = messagebox.askyesno(
                        "提示：",
                        "检测到微信进程正在运行！\r\n必须关闭当前微信后才能多开微信！\r\n是否自动关闭当前微信并进行多开？",
                    )

                if result:
                    # 杀死进程
                    kill_wechat = True
                    proc.kill()
                    time.sleep(0.1)
                else:
                    # 退出程序
                    messagebox.showerror("错误：", "取消微信多开！")
                    sys.exit()
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            # 忽略没有访问权限的进程和已经结束的进程
            pass


if __name__ == "__main__":
    # 创建窗口
    root = tk.Tk()
    # 隐藏主窗口
    root.withdraw()

    wechat_exist = 0
    # 从注册表判断微信是否安装
    app_path = get_wechat_path()
    if app_path:
        if os.path.exists(app_path):
            wechat_exist = 1

    # 注册表中未找到微信安装路径，尝试从配置文件中读取
    if wechat_exist == 0:
        # 判断配置文件及微信安装路径是否存在
        if os.path.exists("config.ini"):
            config = get_config()
            app_path = get_config_value("setting", "path", default_value=None)
            if os.path.exists(app_path):
                wechat_exist += 1

    # 若均未找到微信安装路径，则弹出对话框让用户选择路径
    if wechat_exist == 0:
        app_path = select_wechat_path()
        if app_path:
            # 写入配置文件
            config = configparser.ConfigParser()
            config.add_section("setting")
            config.set("setting", "path", app_path)
            set_config(config)
            wechat_exist = 1

    # 若微信安装路径存在，则启动微信
    if wechat_exist > 0:
        app_path.replace("/", "\\")
        print("多开微信中……")
        # 杀死微信进程
        kill_wechat_process()
        # 询问打开个数
        num = 1
        user_input = simpledialog.askinteger(
            "提示：", "请输入要打开的微信个数：", parent=root, minvalue=1, maxvalue=10
        )
        if not user_input is None:
            num = user_input

        # 多开微信
        for i in range(num):
            os.system("start " + app_path)
    # 退出程序
    root.destroy()
    sys.exit()
